package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.api.entity.*;
import cn.com.api.entity.ApiT_city;
import cn.com.api.entity.ApiT_delivery_account_state;
import cn.com.api.entity.ApiT_member;
import cn.com.api.entity.ApiT_shipper_account;
import cn.com.api.entity.ApiT_shipping;
import cn.com.api.entity.ApiT_token;
import cn.com.api.mapper.ApiShopsMapper;
import cn.com.api.mapper.ApiT_cityMapper;
import cn.com.api.mapper.ApiT_delivery_account_detailMapper;
import cn.com.api.mapper.ApiT_delivery_account_stateMapper;
import cn.com.api.mapper.ApiT_memberMapper;
import cn.com.api.mapper.ApiT_shipper_accountMapper;
import cn.com.api.mapper.ApiT_shippingMapper;
import cn.com.api.mapper.ApiT_tokenMapper;
import cn.com.api.resultpage.InitSendAccountPage;
import cn.com.api.service.ApiT_delivery_account_stateService;
import cn.com.api.service.ApiT_shipper_accountService;
import cn.com.api.service.StartOnLoadService;
import cn.com.api.service.impl.base.T_shipper_accountServiceImplBase;
import cn.com.util.*;

/**
 * 
 **/
@Service
public class ApiT_shipper_accountServiceImpl extends
		T_shipper_accountServiceImplBase implements ApiT_shipper_accountService {
	@Autowired
	private ApiT_shipper_accountMapper apiT_shipper_accountMapper;
	@Autowired
	private ApiT_shippingMapper apiT_shippingMapper;
	@Autowired
	private ApiT_delivery_account_detailMapper apiT_delivery_account_detailMapper;
	@Autowired
	private ApiT_delivery_account_stateMapper apiT_delivery_account_stateMapper;
	@Autowired
	private ApiT_delivery_account_stateService apiT_delivery_account_stateService;
	@Autowired
	private StartOnLoadService startOnLoadService;
	@Autowired
	private ApiT_memberMapper apiT_memberMapper;
	@Autowired
	private ApiT_tokenMapper apiT_tokenMapper;
	@Autowired
	private ApiT_cityMapper apiT_cityMapper;
	@Autowired
	private ApiShopsMapper apiShopsMapper;
	
	public Map<String,Object> findShipperInfoByC_id(String c_id){
		Map<String,Object> shipper = apiT_shipper_accountMapper.findShipperInfoByC_id(c_id);
		return shipper;
	}

	public List<ApiT_shipper_account> find_shipper_atwork() {
		return apiT_shipper_accountMapper.findShipperAtWork();
	}
	
	@Override
	public List<Map<String, Object>> selectShipperAtWork() {
		//
		List<Map<String, Object>> shipper = apiT_shipper_accountMapper
				.selectShipperAtWork();
		return shipper;
	}

	@Override
	public void getMyCount(Map<String, String> params, Map<String, Object> map) {
		String u_id = params.get("u_id");
		/**
		 * 配送费收入 、配送奖励、其他奖励、纠错、货到付款、已提现金额、账户余额
		 * 目前 这些统计信息都是本月的
		 * 没有提现--已提现金额--不用了
		 * 根据u_id  查询当月订单数   3星好评数量  4星好评数量  5星好评数量----计算的配送费收入  配送奖励
		 * 
		 */
		Double sendAward = 0.0;//配送费收入
		BigDecimal orderCash=BigDecimal.ZERO;//货到付款金额
		BigDecimal accountCash =BigDecimal.ZERO;//账户余额
		Double otherAwark = 0.0;//其他奖励
		Double errorAwark = 0.0;//纠错奖励
		/** *星-数量 */
		Integer fourCount = 0;
		Integer fiveCount = 0;
		//--1-四星，五星奖励从 分站取，，  2-基本工资从个人基本信息取  3-超时订单不计奖励
		//查询配送员的账户信息  根据u_id 查询
		ApiT_shipper_account shipAccount = apiT_shipper_accountMapper.selectShipperAccountByUid(u_id);
		//查询配送员的分站信息  city 根据u_id
		ApiT_city city = apiT_cityMapper.findT_cityBySendUid(u_id);
		
		
		double fourAward = city.getSend_fouraward();//配送奖励  4星每单奖励金额
		double fiveAward = city.getSend_fiveaward();//配送奖励  5星每单奖励金额
		double sendFeeIncome = shipAccount.getBasic_wage();//配送奖励  5星每单奖励金额
		
		//--还需要查询评分信息---根据时间    u_id  
		String nowDate = new SimpleDateFormat("yyyy-MM").format(new Date());
		List<Map<String,Object>> resultsMap = apiT_shippingMapper.searchShippingRemarkByTimeAndUidAward(nowDate, u_id);
		if(resultsMap!=null && resultsMap.size()>0){
			for(Map<String, Object> maps : resultsMap){
				Integer grade = Integer.parseInt(maps.get("grade").toString());
				Integer count = Integer.parseInt(maps.get("count").toString());
				if(4==grade){
					fourCount = count;
				}
				if(5==grade){
					fiveCount = count;
				}
			}
		}
		sendAward = fourCount*fourAward + fiveCount*fiveAward;
		orderCash = shipAccount.getOrder_cash();
		accountCash = shipAccount.getMoney();
		
		//查询其他奖励信息   根据u_id  当月时间     纠错奖励    其他奖励  type:0-其他 1-纠错
		resultsMap = apiT_delivery_account_detailMapper.selectSumCashByUidAndTime(u_id, nowDate);
		if(resultsMap!=null && resultsMap.size()>0){
			for(Map<String, Object> maps : resultsMap){
				Integer type = Integer.parseInt(maps.get("type").toString());
				Double money = Double.parseDouble(maps.get("money").toString());
				if(0==type){//其他奖励
					otherAwark = money;
				}
				if(1==type){//纠错
					errorAwark = money;
				}
			}
		}
		
		InitSendAccountPage initSendAccountPage = new InitSendAccountPage();
		initSendAccountPage.setSendFeeIncome(sendFeeIncome);
		initSendAccountPage.setSendAward(sendAward);
		initSendAccountPage.setOtherAward(otherAwark);
		initSendAccountPage.setErrorAward(errorAwark);
		initSendAccountPage.setOrderCash(orderCash);
		initSendAccountPage.setAccountCash(accountCash);
		initSendAccountPage.setWithdrawCash(0.0);
		map.put("datas", initSendAccountPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/** 查询配送员的在离岗状态信息   当天的 */
	@Override
	public void getShipperStatus(Map<String, String> params,
			Map<String, Object> map) {
		String u_id = params.get("u_id");
		

		Integer onGuardTimeM = 0;
		Integer restTimeM = 0;
		Integer postTimeM = 0;
		
		Double onGuardTime = 0.0;
		Double restTime = 0.0;
		Double postTime = 0.0;
		
		//根据日期查询当天所有的信息
		String currDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		List<Map<String,Object>> resultsMap = apiT_delivery_account_stateMapper.selectCurrentDaySumInfoByDate(u_id, currDate);
		if(resultsMap!=null && resultsMap.size()>0){
			for(Map<String,Object> res : resultsMap){
				Integer duration = Integer.parseInt(res.get("duration").toString());//持续时间
				String curr_status = res.get("curr_status").toString();//当前状态
				if("0".equals(curr_status)){//离岗
					postTimeM = postTimeM + duration;
				}
				if("1".equals(curr_status)){//在岗
					onGuardTimeM = onGuardTimeM + duration;
				}
				if("2".equals(curr_status)){//小休
					restTimeM = restTimeM + duration;
				}
			}
		}
		System.out.println("数据库查询分钟：onGuardTime-"+onGuardTimeM+"postTime-"+postTimeM+"restTime"+restTimeM);
		
		//查询当前状态的持续时间
		ApiT_delivery_account_state deliveryAccount = apiT_delivery_account_stateMapper.selectRecentlyRecordByDate(u_id, currDate);
		ApiT_shipper_account shipAccount = apiT_shipper_accountMapper.selectShipperAccountByUid(u_id);
		String currStatus = shipAccount.getWorking_status();//当前最新状态
		int durationRecently = 0;//最近状态的持续时间
		Date startTime = null;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			if(deliveryAccount==null){//如果当天没有改变过状态  从0:00开始计算
				startTime =  dateFormat.parse(currDate+" 00:00:00");
			}else{
				startTime = deliveryAccount.getChange_time();//当天改变过，从改变时间算起
			}
			long nm = 1000 * 60;
			durationRecently = (int) ((new Date().getTime()-startTime.getTime())/ nm);
			if("0".equals(currStatus)){//离岗
				postTimeM = postTimeM + durationRecently;
			}
			if("1".equals(currStatus)){//在岗
				onGuardTimeM = onGuardTimeM + durationRecently;
			}
			if("2".equals(currStatus)){//小休
				restTimeM = restTimeM + durationRecently;
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		onGuardTime = onGuardTimeM/60.0;
		postTime = postTimeM/60.0;
		restTime = restTimeM/60.0;
		
		BigDecimal temp = new BigDecimal(onGuardTime);  
		onGuardTime = temp.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

		temp = new BigDecimal(postTime);  
		postTime = temp.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
		
		temp = new BigDecimal(restTime);  
		restTime = temp.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
		
		
		Map<String, Object> results = new HashMap<String, Object>();
		results.put("onGuardTime", onGuardTime);//在岗
		results.put("restTime", restTime);//小休
		results.put("postTime", postTime);//离岗
		
		map.put("datas", results);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	/** 修改配送员的在离岗状态  */
	@Override
	public void modifyShipperStatus(Map<String, String> params,
			Map<String, Object> map) {
		String u_id = params.get("u_id");
		//0： 离岗 1：在岗 2：小休
		Integer status = Integer.parseInt(params.get("status"));
		//根据u_id 查询配送员信息
		apiT_delivery_account_stateService.loginChangeState(u_id, status);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "修改成功！");
		
	}

	@Override
	//后台配送员列表
	public List<Member_shipper> m_shipperlist(PageInfo pageInfo) {
		
		return apiT_shippingMapper.m_shipperlistListPage(pageInfo);
	}

	@Override
    //立即派单配送员列表
	public List<Shipper_list> Shippers_pd(String orderId,PageInfo pageInfo) {
		List<Shipper_list> Shippers_pd=new ArrayList<Shipper_list>();
		ApiShop shop = apiShopsMapper.getShopByOrderId(orderId);
		Integer city_id = shop.getC_city_id();
		List<ApiT_shipper_account> shippers= apiT_shipper_accountMapper.findShipperAtWorkByCityIdListPage(city_id, pageInfo);
		if(!shippers.isEmpty()){
			for(ApiT_shipper_account shipper:shippers){
				Shipper_list shipper_pd=new Shipper_list();
				shipper_pd.setUser_id(shipper.getUser_id());
				ApiT_member member=apiT_memberMapper.findT_membersByUserid(shipper.getUser_id());
				if(member!=null){
					shipper_pd.setC_tname(member.getC_tname());
					if(member.getC_city()!=null&&!member.getC_city().equals("")){
						ApiT_city city=apiT_cityMapper.findT_cityById(Integer.parseInt(member.getC_city()));
						if(city!=null){
							shipper_pd.setC_city(city.getName());
						}
					}
					shipper_pd.setC_mob(member.getC_mob());
				}
				ApiT_token token=apiT_tokenMapper.selectApiT_tokenByUidAndRole(Integer.valueOf(shipper.getUser_id()), 3);
				if(token!=null){
					shipper_pd.setLatitude(token.getLatitude());
					shipper_pd.setLongitude(token.getLongitude());
				}
				shipper_pd.setWorking_status(shipper.getWorking_status());
				List<ApiT_shipping> shippings=apiT_shippingMapper.shipbyuiding(shipper.getUser_id());
				String titlesString="";
				if(!shippings.isEmpty()){
					for(ApiT_shipping ship:shippings){
						titlesString=titlesString+ship.getOrder_id()+",";
					}
				}
				shipper_pd.setTitles(titlesString);
				List<ApiT_shipping> shippings2=apiT_shippingMapper.shipbyuidend(shipper.getUser_id());
				int remark=0; int ontime=0;
				if(!shippings2.isEmpty()){
					for(ApiT_shipping ship:shippings2){
						if(ship.getShipping_remark()>=4){
							remark++;
						}
						if(ship.getIs_ontime()==0){
							ontime++;
						}
					}
					shipper_pd.setRemark(String.valueOf((int)(remark/shippings2.size()*100)));
					shipper_pd.setOntime(String.valueOf((int)(ontime/shippings2.size()*100)));
				}
				Shippers_pd.add(shipper_pd);
			}
		}
		return Shippers_pd;
	}
	
	@Override
    //更改派单配送员列表
	public List<Shipper_list> Shippers_change_pd(String shippingId,String orderId,PageInfo pageInfo) {
		List<Shipper_list> Shippers_pd=new ArrayList<Shipper_list>();
		ApiShop shop = apiShopsMapper.getShopByOrderId(orderId);
		Integer city_id = shop.getC_city_id();
		List<ApiT_shipper_account> shippers= apiT_shipper_accountMapper.findShipperAtWorkByCityIdListPage(city_id, pageInfo);
		ApiT_shipping shipping=apiT_shippingMapper.findT_shippingById(Integer.parseInt(shippingId));
		if(!shippers.isEmpty()){
			for(ApiT_shipper_account shipper:shippers){
				if(!shipper.getUser_id().equals(shipping.getUser_id())){
					Shipper_list shipper_pd=new Shipper_list();
					shipper_pd.setUser_id(shipper.getUser_id());
					ApiT_member member=apiT_memberMapper.findT_membersByUserid(shipper.getUser_id());
					if(member!=null){
						shipper_pd.setC_tname(member.getC_tname());
						if(member.getC_city()!=null&&!member.getC_city().equals("")){
							ApiT_city city=apiT_cityMapper.findT_cityById(Integer.parseInt(member.getC_city()));
							if(city!=null){
								shipper_pd.setC_city(city.getName());
							}
						}
						shipper_pd.setC_mob(member.getC_mob());
					}
					ApiT_token token=apiT_tokenMapper.selectApiT_tokenByUidAndRole(Integer.valueOf(shipper.getUser_id()), 3);
					if(token!=null){
						shipper_pd.setLatitude(token.getLatitude());
						shipper_pd.setLongitude(token.getLongitude());
					}
					shipper_pd.setWorking_status(shipper.getWorking_status());
					List<ApiT_shipping> shippings=apiT_shippingMapper.shipbyuiding(shipper.getUser_id());
					String titlesString="";
					if(!shippings.isEmpty()){
						for(ApiT_shipping ship:shippings){
							titlesString=titlesString+ship.getOrder_id()+",";
						}
					}
					shipper_pd.setTitles(titlesString);
					List<ApiT_shipping> shippings2=apiT_shippingMapper.shipbyuidend(shipper.getUser_id());
					int remark=0; int ontime=0;
					if(!shippings2.isEmpty()){
						for(ApiT_shipping ship:shippings2){
							if(ship.getShipping_remark()>=4){
								remark++;
							}
							if(ship.getIs_ontime()==0){
								ontime++;
							}
						}
						shipper_pd.setRemark(String.valueOf((int)(remark/shippings2.size()*100)));
						shipper_pd.setOntime(String.valueOf((int)(ontime/shippings2.size()*100)));
					}
					Shippers_pd.add(shipper_pd);
				}
			}
		}
		return Shippers_pd;
	}

	@Override
	//多条件查询配送员
	public List<Member_shipper> shipper_list_bytermListPage(
			Map<String, Object> conditions, PageInfo pageInfo) {
		
		return apiT_shippingMapper.shipper_list_bytermListPage(conditions, pageInfo);
	}
}
